//
//  LogisticsVc.swift
//  Pods
//
//  Created by eme on 2017/4/5.
//
//

import UIKit
import UtilCore
import EmptyDataView
import RickonCore

class LogisticsVc: Empty_TVc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var TopView: UIView!                         //顶部按钮View
    
    @IBOutlet weak var CustomTableView: UITableView!            //数据列表
    
    @IBOutlet weak var custom_ScrollView: UIScrollView!         //滑动视图
    
    @IBOutlet weak var tableViewWithTop: NSLayoutConstraint!
    
    var contentView = UIView()
    var resultArr:[LogisticsModel]?{                            //数据源
        didSet{
            self.CustomTableView.reloadData()
        }
    }
    
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var LogisticsVm:OrderLogisticsVm?                           //获取物流ViewModel
    
    var orderid:String?                                         //订单ID
    
    var topButtonArr = [UIButton]()                             //顶部按钮数组
    
    var blackView = UIView()                                    //黑色的View
    
    var Customsection = 0
    
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.LogisticsVm?.getOrderLogistics.onNext(self.orderid!)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        //添加空数据代理(品牌)
        self.CustomTableView.dzn_tv_emptyDelegate = self
        self.CustomTableView.dzn_tv_emptyDataSource = self
        self.CustomTableView.tableFooterView = UIView()
        
        self.customLeftBarButtonItem()
        self.setUpCollectionView()
        self.setCustom_ScrollView()
        
    }
    func setUpCollectionView(){
        
        self.CustomTableView.showsVerticalScrollIndicator = false
        self.CustomTableView.delegate = self
        self.CustomTableView.dataSource = self
        self.CustomTableView.estimatedRowHeight = 100
        self.CustomTableView.rowHeight = UITableViewAutomaticDimension
        self.CustomTableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.1))
        
    }
    func setCustom_ScrollView(){
        self.custom_ScrollView.addSubview(self.contentView)
        self.contentView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalTo(0)
            make.height.equalTo(self.custom_ScrollView)
        }
    }
    func setOtherTableView(){
        
        if self.resultArr?.count != 0
        {
            if self.resultArr?.count == 1{
                
                self.TopView.isHidden = true
                self.tableViewWithTop.constant = -43
                
            }else{
                
                for index in 0...(self.resultArr?.count)! - 1{
                    
                    let button = UIButton(type: .custom)
                    button.setTitle("包裹\(index + 1)", for: .normal)
                    button.addTarget(self, action: #selector(LogisticsVc.topButtonClicked(_:)), for: .touchUpInside)
                    button.tag = index
                    
                    if index == 0{
                        
                        button.setTitleColor(UIColor(hex: "333333"), for: .normal)
                    }else{
                        button.setTitleColor(UIColor(hex: "999999"), for: .normal)
                    }
                    button.titleLabel?.normal_fontSize(13)
                    
                    self.topButtonArr.append(button)
                    self.contentView.addSubview(button)
                    
                    button.snp.makeConstraints({ (make) in
                        
                        make.height.equalTo(15)
                        make.left.equalTo(15 + 55 * index)
                        make.bottom.equalTo(self.contentView.snp.bottom).offset(-12.5)
                        if index == (self.resultArr?.count)! - 1{
                            make.right.equalTo(-15)
                        }
                        
                    })
                }
                for index in 1...self.topButtonArr.count - 1{
                    
                    let line = UIView()
                    line.backgroundColor = UIColor(hex: "e6e6e6")
                    self.TopView.addSubview(line)
                    line.snp.makeConstraints({ (make) in
                        make.left.equalTo(self.topButtonArr[index - 1].snp.right).offset(12.5)
                        make.width.equalTo(0.5)
                        make.bottom.equalTo(9)
                    })
                }
                
                self.blackView.backgroundColor = UIColor.black
                self.contentView.addSubview(self.blackView)
                self.blackView.snp.makeConstraints({ (make) in
                    make.centerX.equalTo(self.topButtonArr[0].snp.centerX)
                    make.bottom.equalTo(self.TopView.snp.bottom)
                    make.width.equalTo(35)
                    make.height.equalTo(2)
                })
            }
        }
        
    }
    //顶部按钮点击事件
    
    func topButtonClicked(_ sender:UIButton){
        
        self.Customsection = sender.tag
        
        for btn in topButtonArr{
            
            if btn.tag == sender.tag{
                
                self.blackView.center.x = sender.center.x
                btn.setTitleColor(UIColor.black, for: .normal)
                
            }else{
                
                btn.setTitleColor(UIColor(hex: "999999"), for: .normal)
            }
        }
        self.CustomTableView.reloadData()
    }
    func copyOrderid(_ sender:UIButton){
        UIPasteboard.general.string = self.resultArr?[Customsection].logisticsnumber
        self.view.makeToast("复制成功")

    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        self.LogisticsVm = OrderLogisticsVm()
        
        self.LogisticsVm?.backDate.asObserver().subscribe(onNext:{ [unowned self] data in
            
            self.showEmptyView = true
            self.resultArr = data
            self.setOtherTableView()
            
        }).addDisposableTo(disposeBag)
        //加载动画
        self.LogisticsVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        //显示错误
        self.LogisticsVm?.error.asObservable().bindTo(self.view.rx_error).addDisposableTo(disposeBag)

        
    }
}
extension LogisticsVc:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let resultData = self.resultArr{
            if resultData[Customsection].kuaidi.status != "0"{
                return 2
            }else{
                return resultData[Customsection].kuaidi.result.list.count + 1
            }
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! LogisticsRow_TableViewCell
        let newCell = tableView.dequeueReusableCell(withIdentifier: "wlCell") as! WLCellTableViewCell
        
        
        if indexPath.row == 0{
            guard #available(iOS 9.0, *) else {
                newCell.setNeedsUpdateConstraints()
                newCell.updateConstraintsIfNeeded()
                return newCell
            }
            return newCell
        }else{
            
            if self.resultArr?[Customsection].kuaidi.status == "0"{
                
                if indexPath.row == 1 && self.resultArr?[Customsection].kuaidi.result.deliverystatus == "3"{
                    
                    cell.yuan_Width.constant = 19
                    cell.Yuan_ImageView.image = UIImage(named: "WL_Image", in: SansaCore.bundle, compatibleWith: nil)
                    cell.yuan_Withleft.constant = 15
                    cell.messageLabel.textColor = UIColor(hex: "ff8683")
                    cell.timeLabel.textColor = UIColor(hex: "ff8683")
                    
                }else{
                    cell.yuan_Width.constant = 7
                    cell.Yuan_ImageView.image = UIImage(named: "yuan_Image", in: SansaCore.bundle, compatibleWith: nil)
                    cell.yuan_Withleft.constant = 21
                    cell.messageLabel.textColor = UIColor(hex: "333333")
                    cell.timeLabel.textColor = UIColor(hex: "333333")
                }
                if indexPath.row == self.resultArr?[Customsection].kuaidi.result.list.count{
                    cell.SHU_View.isHidden = true
                }else{
                    cell.SHU_View.isHidden = false
                }
                cell.item = self.resultArr?[Customsection].kuaidi.result.list[indexPath.row - 1]
            }else{
                
                cell.messageLabel.text = self.resultArr?[Customsection].kuaidi.msg
                cell.timeLabel.text = ""
                cell.SHU_View.isHidden = true
            }
            guard #available(iOS 9.0, *) else {
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
                return cell
            }
            return cell
        }
        
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! Logistics_HeaderTableViewCell
        
        if let result = self.resultArr{
            
            cell.item = result[Customsection]
            cell.status = result[Customsection].kuaidi.result.deliverystatus
            cell.copy_Button.tag = Customsection
            cell.copy_Button.addTarget(self, action: #selector(LogisticsVc.copyOrderid(_:)), for: .touchUpInside)
        }
        guard #available(iOS 9.0, *) else {
            cell.setNeedsUpdateConstraints()
            cell.updateConstraintsIfNeeded()
            return cell
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 116
    }
}
extension LogisticsVc:EmptyDataSource{
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString? {
        return Theme.getEmptyDesc("获取不到物流信息～")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage? {
        return UIImage.init(named: "Listkong_Image", in: SansaCore.bundle, compatibleWith: nil)
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
}
